from flask import Flask, request, json
from flask_restplus import Api
from model import User, Doc
from config import db
from os import path
from config import APP_ROOT
import hashlib
app = Flask(__name__)

@app.route('/')
def hello_world():
    print(i)
    return 'Hello World!'

@app.route('/hello')
def hello():
    return 'Hello World'

@app.route('/upload', methods= ['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['content']
        md5 = get_file_md5(f)
        flie_path = path.join(APP_ROOT, 'upload', md5)
        f.seek(0)
        f.save(flie_path)
        print(f)
        return md5
    res = 'upload success'
    return res

def get_file_md5(f):
    m = hashlib.md5()

    while True:
        data = f.read(10240)
        if not data:
            break

        m.update(data)
    return m.hexdigest()
# me = User(
#     username='admin',
#     email='admin@example.com',
#     role='admin',
#     password_hash='aaa'
# )
# db.session.add(me)
# db.session.commit()

# doc = Doc(
#     title= 'manga11',
#     content= 'galgame history11',
#     user_id= 1,
# )
# db.session.add(doc)
# db.session.commit()

# q = db.session.query(User.username).join(Doc.title) \
#     .filter(Doc.user_id == User.id)
# result = db.session.execute(q)
# for row in result:
#     print(row)

app.debug = True

if __name__ == '__main__':
    app.run()